package com.example.demo.Config.Controllerhandler;

import com.example.demo.Utils.Result.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.rmi.AccessException;

@ControllerAdvice
public class ControllerHandler {

    /**
     * 处理 HTTP 404 错误
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public R handleNotFound(HttpServletRequest req, Exception ex) {
        return R.notFound("无该资源: " + req.getRequestURI());
    }

    /**
     * 处理 HTTP 500 错误
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public R handleInternalServerError(HttpServletRequest req, Exception ex) {
        return R.error("服务器内部错误: " + ex.getMessage());
    }

    /**
     * 处理权限不足异常（使用更具体的 AccessDeniedException）
     */
    @ExceptionHandler(AccessException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public R handleNoAuth(HttpServletRequest req, AccessException ex) {
        return R.forbidden(ex.getMessage());
    }

    /**
     * 处理其他所有未处理的异常（保留处理 Throwable 的方法，但确保不冲突）
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public R handleOtherExceptions(HttpServletRequest req, Throwable ex) {
        return R.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误: " + ex.getMessage());
    }
}